package com.chezai.client.dao.manager;

import android.content.Context;
import android.util.SparseArray;

import com.chezai.client.R;
import com.chezai.client.bean.TrainProjectEntity;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 培训项目管理类
 * Created by likunyang on 2017/8/31.
 */

public class TrainProjectEntityManager {
    private static TrainProjectEntityManager newInstance;
    private SparseArray<List<TrainProjectEntity>> entitySparseArray;

    private TrainProjectEntityManager() {
        entitySparseArray = new SparseArray<>(4);
    }

    public static TrainProjectEntityManager getInstance() {
        if (newInstance == null) {
            newInstance = new TrainProjectEntityManager();
        }
        return newInstance;
    }

    /**
     * 根据培训部分，获取该培训部分下的培训项目
     *
     * @param part see TrainProjectEntity RAIN_PART_ONE 等
     * @return
     */
    public List<TrainProjectEntity> getTrainProjectsByPart(Context context, int part) {
        List<TrainProjectEntity> trainProjectEntities = entitySparseArray.get(part);
        if (trainProjectEntities != null) {
            return trainProjectEntities;
        }
        SoftReference<Context> softReference = new SoftReference<>(context);
        if (softReference.get() != null) {
            String[] trainProjectArr = new String[]{};
            switch (part) {
                case TrainProjectEntity.TRAIN_PART_ONE:
                    trainProjectArr = softReference.get().getResources().getStringArray(R.array.train_part_one);
                    break;
                case TrainProjectEntity.TRAIN_PART_TWO:
                    trainProjectArr = softReference.get().getResources().getStringArray(R.array.train_part_two);
                    break;
                case TrainProjectEntity.TRAIN_PART_THREE:
                    trainProjectArr = softReference.get().getResources().getStringArray(R.array.train_part_three);
                    break;
                case TrainProjectEntity.TRAIN_PART_FOUR:
                    trainProjectArr = softReference.get().getResources().getStringArray(R.array.train_part_four);
                    break;
            }
            int arrLength = trainProjectArr.length;
            trainProjectEntities = new ArrayList<>(arrLength);
            for (int i = 0; i < arrLength; i++) {
                String project = trainProjectArr[i];
                String[] split = project.split("-");
                TrainProjectEntity trainProjectEntity = new TrainProjectEntity(split[1], split[0]);
                trainProjectEntities.add(trainProjectEntity);
            }
            entitySparseArray.put(part, trainProjectEntities);
            return trainProjectEntities;
        }
        return Collections.emptyList();
    }
}
